package main

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	"github.com/google/uuid"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"mxshop-api/user-web/global"
	"mxshop-api/user-web/initialize"
	"mxshop-api/user-web/utils"
	"mxshop-api/user-web/utils/register/consul"
	myvalidator "mxshop-api/user-web/validator"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	// 1. 初始化 logger
	initialize.InitLogger()

	// 2. 初始化 配置文件
	initialize.InitConfig()

	// 3. 初始化 routers
	Routser := initialize.Routers()

	// 4. 初始化 验证翻译
	if err := initialize.InitTrans("zh"); err != nil {
		zap.S().Panic(err)
	}

	// 5. 初始化 srv 的连接
	initialize.InitSrvConn()

	// 6. 初始化 sentinel 熔断限流
	initialize.InitSentinel()

	// 如果是本地开发环境端口号固定， 现实环境启动获取端口号
	viper.AutomaticEnv()
	debug := viper.GetBool("MXSHOP_DEBUG")
	if !debug {
		if port, err := utils.GetFreePort(); err == nil {
			global.ServerConfig.Port = port
		}
	}

	//注册验证器
	// 这里 gin 绝对封装了一层 validator 库
	// github.com\gin-gonic\gin@v1.8.1\binding\default_validator.go 声明了 Validate
	// 因为 validator 库 原生代码是这么写的
	// https://github.com/go-playground/validator/blob/master/_examples/custom-validation/main.go
	// https://github.com/go-playground/validator/blob/master/_examples/translations/main.go
	// validate = validator.New()
	// validate.RegisterValidation("mobile", myvalidator.ValidateMobile)
	// validate.RegisterTranslation...
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("mobile", myvalidator.ValidateMobile)
		// https://github.com/go-playground/validator/blob/v9/_examples/translations/main.go#L105
		v.RegisterTranslation("mobile", global.Trans, func(ut ut.Translator) error {
			return ut.Add("mobile", "{0} 非法的手机号码!", true) // see universal-translator for details
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("mobile", fe.Field())
			return t
		})
	}

	registerClient := consul.NewRegistryClient(global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port)
	serviceId := fmt.Sprintf("%s", uuid.New())
	err := registerClient.Register(global.ServerConfig.Host, global.ServerConfig.Port, global.ServerConfig.Name, global.ServerConfig.Tags, serviceId)
	if err != nil {
		zap.S().Panic("[user-web] 服务注册失败:", err.Error())
	}
	zap.S().Debugf("[user-web] 启动服务器, 端口: %d", global.ServerConfig.Port)
	go func() {
		if err := Routser.Run(fmt.Sprintf(":%d", global.ServerConfig.Port)); err != nil {
			zap.S().Panic("[user-web] 服务启动失败:", err.Error())
		}
	}()
	// 接收终止信号
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = registerClient.DeRegister(serviceId); err != nil {
		zap.S().Panic("[user-web] 服务注销失败:", err.Error())
	} else {
		zap.S().Info("[user-web] 服务注销成功")
	}
}
